<?php

namespace App\Api\Phalapitencentsms;
use PhalApi\Api;
use App\Domain\Phalapitencentsms\Main as SmsDomain;
use PhalApi\Exception\BadRequestException;

/**
 * 腾讯云短信接口
 * @desc 包含发送短信和验证验证码的接口
 */
class Sms extends Api
{
    public function getRules()
    {
        return array(
            'sendSMS' => array(
                'username' => array('name' => 'phone', 'type' => 'string', 'require' => true, 'desc' => '用户名(手机号)'),
            ),
            'checkSMS' => array(
                'username' => array('name' => 'phone', 'type' => 'string', 'require' => true, 'desc' => '用户名(手机号)'),
                'code' => array('name' => 'verifyCode', 'type' => 'string', 'require' => true, 'desc' => '验证码'),
            ),
            'reSMS' => array(
                'username' => array('name' => 'username', 'type' => 'string', 'require' => true, 'desc' => '用户名(手机号)'),
            ),
            'addphoneSMS' => array(
                'mobile' => array('name' => 'mobile', 'type' => 'string', 'require' => true, 'desc' => '用户名(手机号)'),
            ),
        );  
    }

    function generateRandomString() {
        $randomString = '';
        for ($i = 0; $i < 6; $i++) {
            $randomNumber = rand(0, 9);
            $randomString .= $randomNumber;
        }
        return $randomString;
    }

    /**
     * 发送短信验证码
     * @desc 向指定手机号发送短信验证码
     * @return string
     */
    public function sendSMS()
    {
        // 检查手机号是否为空
        if(!$this->username){
            throw new BadRequestException('手机号不能为空');
        }

        // 检查用户是否存在
        $domain = new \App\Domain\User\User();
        $user = $domain->getUserByUsername($this->username, 'id');
        if (!$user) {
            throw new BadRequestException($this->username . '账号不存在');
        }

        // 检查缓存中是否已有未过期的验证码
        // 防止短时间内重复发送验证码
        if (\PhalApi\DI()->cache->get($this->username)) {
            throw new BadRequestException('生效期内，验证码已发送，请稍后再试', 1);
        }

        $sms = new SmsDomain();
        $smsCode = $this->generateRandomString(); // 随机生成4位短信验证码
        $templateParam = array($smsCode);
        $sdkAppId = '1400959738'; // 请替换为实际的 SdkAppId
        $signName = '郴州守望科技';
        $templateId = '2346659';

        // 调用腾讯云发短信接口
        $data = $sms->tencentSendSms($this->username, $templateId, $templateParam, $sdkAppId, $signName);

        $responseData = json_decode($data, true);
        if ($responseData && $responseData['SendStatusSet'][0]['Code'] === 'Ok') {
            // 设置验证码到缓存，有效期 600 秒
            \PhalApi\DI()->response->setMsg('发送成功');
            \PhalApi\DI()->cache->set($this->username, $smsCode, 600);
            return "发送成功";
        } else {
            throw new BadRequestException($responseData['SendStatusSet'][0]['Message'] ?? '短信发送失败', 1);
        }
    }

    /**
     * 验证短信验证码
     * @desc 验证指定手机号的短信验证码是否正确
     * @return string
     */
    public function checkSMS()
    {
        if(!$this->username){
            throw new BadRequestException('手机号不能为空');
        }
        if(!$this->code){
            throw new BadRequestException('验证码不能为空');
        }

        $cachedCode = \PhalApi\DI()->cache->get($this->username);
        if ($cachedCode === $this->code) {
            \PhalApi\DI()->response->setMsg('验证成功');
            
            // 验证成功后，清除验证码缓存
            // \PhalApi\DI()->cache->delete($this->username);
            
            // 获取用户信息
            $domain = new \App\Domain\User\User();
            $user = $domain->getUserByUsername($this->username, 'id');
            $user_id = intval($user['id']);
            
            // 生成会话token
            $session = new \App\Domain\User\UserSession();
            $token = $session->generate($user_id);
            
            $profile = $domain->getUserByUsername($this->username, '*');
            $roles = json_decode($profile['roles'] ?? '[]', true);
            
            \PhalApi\DI()->response->addResult('success', true);

            return array(
                'is_login' => true,
                'user_id' => $user_id,
                'token' => $token,
                'avatar' => $profile['avatar'] ?? "https://img.wenfree.cn/logo/logo-yunkong.png",
                'username' => $this->username,
                'nickname' => $profile['nickname'] ?? '',
                'roles' => is_array($roles) ? $roles : [],
                'permissions' => array("read:system", "write:system", "delete:system"),
                'accessToken' => $token,
                'refreshToken' => $token,
                'expires' => date('Y/m/d H:i:s', strtotime('+7 days'))
            );
        } else {
            throw new BadRequestException('验证码错误或已过期', 1);
        }
    }

    /**
     * 发送改密短信验证码
     * @desc 向指定手机号发送短信验证码
     * @return string
     */
    public function reSMS()
    {
        // 检查手机号是否为空
        if(!$this->username){
            throw new BadRequestException('手机号不能为空');
        }

        // 检查用户是否存在
        $domain = new \App\Domain\User\User();
        $user = $domain->getUserByUsername($this->username, 'id');
        if (!$user) {
            throw new BadRequestException($this->username . '账号不存在');
        }

        // 检查缓存中是否已有未过期的验证码
        // 防止短时间内重复发送验证码
        if (\PhalApi\DI()->cache->get($this->username)) {
            throw new BadRequestException('生效期内，验证码已发送，请稍后再试', 1);
        }

        $sms = new SmsDomain();
        $smsCode = $this->generateRandomString(); // 随机生成4位短信验证码
        $templateParam = array($smsCode);
        $sdkAppId = '1400959738'; // 请替换为实际的 SdkAppId
        $signName = '郴州守望科技';
        $templateId = '2346662';

        // 调用腾讯云发短信接口
        $data = $sms->tencentSendSms($this->username, $templateId, $templateParam, $sdkAppId, $signName);

        $responseData = json_decode($data, true);
        if ($responseData && $responseData['SendStatusSet'][0]['Code'] === 'Ok') {
            // 设置验证码到缓存，有效期 600 秒
            \PhalApi\DI()->response->setMsg('发送成功');
            \PhalApi\DI()->cache->set($this->username, $smsCode, 600);
            return "发送成功";
        } else {
            throw new BadRequestException($responseData['SendStatusSet'][0]['Message'] ?? '短信发送失败', 1);
        }
    }



    /**
     * 添加任务手机
     * @desc 发送短信
     * @param string $phone 手机号
     * @param string $type 短信类型
     * @param string $SignName 签名名称
     * @param string $TemplateCode 模版CODE
     * @param string $TemplateParam 模版参数
     * @return string
     */
    public function addphoneSMS()
    {

       
        // $phone, $type, $SignName, $TemplateCode, $TemplateParam
        $sms = new SmsDomain();
        // 调用发短信接口
        $type = 'sms_TemplateCode_register'; //短信模版类型
        if(!$this->mobile){
            throw new BadRequestException('手机号不能为空');
        }

        //判断手机号是否已存在
        $phone = \PhalApi\DI()->notorm->phone_list->where(array('mobile'=>$this->mobile ))->fetchOne();

        if( $phone ){
            throw new BadRequestException('该手机号已存在'. $this->mobile);
        }
        

        $phone = $this->mobile;            // 手机号
        $sms = new SmsDomain();
        $smsCode = $this->generateRandomString(); // 随机生成4位短信验证码
        $templateParam = array($smsCode);
        $sdkAppId = '1400959738'; // 请替换为实际的 SdkAppId
        $signName = '郴州守望科技';
        $templateId = '2346663';

        // 调用腾讯云发短信接口
        $data = $sms->tencentSendSms($phone, $templateId, $templateParam, $sdkAppId, $signName);

        $responseData = json_decode($data, true);
        if ($responseData && $responseData['SendStatusSet'][0]['Code'] === 'Ok') {
            // 设置验证码到缓存，有效期 600 秒
            \PhalApi\DI()->response->setMsg('发送成功');
            \PhalApi\DI()->cache->set($this->username, $smsCode, 600);
            return "发送成功";
        } else {
            throw new BadRequestException($responseData['SendStatusSet'][0]['Message'] ?? '短信发送失败', 1);
        }
     

    }
}